package com.simtop.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.simtop.common.ServerResponse;
import com.simtop.pojo.User;
import com.simtop.pojo.wddata.MainTain;
import com.simtop.pojo.wddata.WdDate;
import com.simtop.service.ApiService;
import com.simtop.service.MonitoringDataService;
import com.simtop.util.JwtUtil;
import com.simtop.vo.*;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

//设备数据
@RestController
@RequestMapping("/devicedata")
@CrossOrigin
@Component
public class MonitoringDataController {
    @Autowired
    private MonitoringDataService monitoringDataService;

    @Autowired
    private ApiService apiService;

    //获取监控数据
    //从数据维护表中获取
    @PostMapping("/findDeviceData")
    public ServerResponse findDeviceData(@RequestBody String data, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            Integer pageNum = jsonObject.getInteger("pageNum");
            Integer pageSize = jsonObject.getInteger("pageSize");
            if(StringUtils.isEmpty(pageNum) || pageNum == 0){
                pageNum = 1;
            }
            if(StringUtils.isEmpty(pageSize) || pageSize == 0){
                pageSize = 10;
            }
            PageHelper.startPage(pageNum,pageSize);
            String column = jsonObject.getString("column");
            String order = jsonObject.getString("order");
            String deviceNumber = jsonObject.getString("deviceNumber");
            String testType = jsonObject.getString("testType");
            Date readTimeBegin = jsonObject.getDate("readTimeBegin");
            Date readTimeEnd = jsonObject.getDate("readTimeEnd");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String readTimeBegins = null;
            String readTimeEnds = null;
            if(readTimeBegin != null && readTimeEnd != null) {

                readTimeBegins = df.format(readTimeBegin);
                readTimeEnds = df.format(readTimeEnd);
                List<MonitoringDataVo> findAlldeviceListAllBystatus= apiService.findAlldeviceListAllBystatus(column,order,readTimeBegins,readTimeEnds,deviceNumber,testType);
                PageInfo<MonitoringDataVo> pageInfo = new PageInfo<MonitoringDataVo>(findAlldeviceListAllBystatus);
                return ServerResponse.createBySuccess("获取内容成功",pageInfo);
            }



            List<MonitoringDataVo> findAlldeviceListAllBystatus= apiService.findAlldeviceListAllBystatus(column,order,readTimeBegins,readTimeEnds,deviceNumber,testType);
            PageInfo<MonitoringDataVo> pageInfo = new PageInfo<MonitoringDataVo>(findAlldeviceListAllBystatus);
            return ServerResponse.createBySuccess("获取内容成功",pageInfo);
        }
        catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByError();
        }
    }

    //获取监控数据
    //从数据维护表中获取
    @PostMapping("/deleteDeviceData")
    public ServerResponse deleteDeviceData(@RequestBody String data, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        JSONObject jsonObject = JSONObject.parseObject(data);
        String id = jsonObject.getString("id");
        String[] split = id.split(",");
        ArrayList<Integer> sqsyidlist = new ArrayList<>();


        Iterator<String> iterator = Arrays.stream(split).iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            Integer i = Integer.valueOf(next);
            sqsyidlist.add(i);

            // apiService.finOne
        }
        apiService.getStatusList2(sqsyidlist);
        return ServerResponse.createBySuccess();
    }




    @RequestMapping(value = "updateExlxDeviceData",method = RequestMethod.GET)
    public ServerResponse updateExlxDeviceData(String id, HttpServletRequest  request , HttpServletResponse response) {



        try {

            if(id == null){
                try {
               //     System.out.println("西夏哈哈");
                    //找到所有的学生
                    List<MonitoringDataVo> findAlldeviceListAllBystatus= apiService.findAlldeviceListAllBystatus2();



                    ArrayList<MonitoringDataExcelVo> excelVos = new ArrayList<MonitoringDataExcelVo>();
                    for (MonitoringDataVo as:findAlldeviceListAllBystatus
                    ) {
                        MonitoringDataExcelVo monitoringDataExcelVo = new MonitoringDataExcelVo();
                        monitoringDataExcelVo.setId(as.getId());
                        monitoringDataExcelVo.setDeviceNumber(as.getDeviceNumber());
                        monitoringDataExcelVo.setDeviceName(as.getDeviceName());
                        monitoringDataExcelVo.setTestType(as.getTestType());
                        monitoringDataExcelVo.setTestLocation(as.getTestLocation());
                        float deviceValue = as.getDeviceValue();
                        String deviceMark = as.getDeviceMark();
                        String last = deviceValue + deviceMark;
                        monitoringDataExcelVo.setDeviceValue(last);
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String format = sdf.format(as.getReadTime());
                        monitoringDataExcelVo.setReadTime(format);
                        excelVos.add(monitoringDataExcelVo);

                    }


                    ExportParams exportParams = new ExportParams("自动化实时全部数据表单", "自动化实时全部数据表单");//设置sheet
                    Workbook workbook = ExcelExportUtil.exportExcel(exportParams, MonitoringDataExcelVo.class, excelVos);//问好处填vo
                    //String fileName = new String("社群全部成绩数据".getBytes(), "UTF-8") + ".xls";//设置excel的名称后缀
                    //response.setContentType("application/vnd.ms-excel;charset=UTF-8");//类型
                    //response.setHeader("Content-Disposition", "attachment;filename=" + fileName);//设置响应头
                    //response.setCharacterEncoding("UTF-8");//格式
                    String exportFileName ="自动化实时全部数据表单.xlsx";
                    String fileNameURL = URLEncoder.encode(exportFileName, "UTF-8");
                    response.setHeader("Content-disposition", "attachment;filename="+fileNameURL+";"+"filename*=utf-8''"+fileNameURL);

                    //response.setContentType("application/vnd.ms-excel;charset=UTF-8");//类型
                    response.setContentType("application/vnd.ms-excel");
                    OutputStream os = response.getOutputStream();

                    workbook.write(os);//写入
                    os.flush();


                    try {
                        os.close();//关闭
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return ServerResponse.createBySuccess();
                } catch (Exception ex) {
                    ex.printStackTrace();
                    return ServerResponse.createByError();
                }



            }



            String[] split = id.split(",");

            ArrayList<Integer> objects = new ArrayList<>();
            Arrays.stream(split).iterator();



            ArrayList<Integer> sqsyidlist = new ArrayList<>();


            Iterator<String> iterator = Arrays.stream(split).iterator();
            while (iterator.hasNext()) {
                String next = iterator.next();
                Integer i = Integer.valueOf(next);
                sqsyidlist.add(i);

                // apiService.finOne
            }

            for (Integer asa:sqsyidlist
            ) {
            //    System.out.println(asa);
            }


            List<MonitoringDataVo> findAlldeviceListAllBystatus= apiService.findAlldeviceListAllBystatus3(sqsyidlist);


            ArrayList<MonitoringDataExcelVo> excelVos = new ArrayList<MonitoringDataExcelVo>();
            for (MonitoringDataVo as:findAlldeviceListAllBystatus
            ) {
                MonitoringDataExcelVo monitoringDataExcelVo = new MonitoringDataExcelVo();
                monitoringDataExcelVo.setId(as.getId());
                monitoringDataExcelVo.setDeviceNumber(as.getDeviceNumber());
                monitoringDataExcelVo.setDeviceName(as.getDeviceName());
                monitoringDataExcelVo.setTestType(as.getTestType());
                monitoringDataExcelVo.setTestLocation(as.getTestLocation());
                float deviceValue = as.getDeviceValue();
                String deviceMark = as.getDeviceMark();
                String last = deviceValue + deviceMark;
                monitoringDataExcelVo.setDeviceValue(last);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = sdf.format(as.getReadTime());
                monitoringDataExcelVo.setReadTime(format);
                excelVos.add(monitoringDataExcelVo);

            }


            ExportParams exportParams = new ExportParams("自动化实时数据表单", "自动化实时数据表单");//设置sheet
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, MonitoringDataExcelVo.class, excelVos);//问好处填vo
            //String fileName = new String("社群成绩".getBytes(), "ISO8859-1") + ".xls";//设置excel的名称后缀
            //String fileNames = "社群用户成绩.xls";
            // fileNames= new String((fileNames).getBytes(), "UTF-8");
            String exportFileName ="自动化实时数据表单.xlsx";
            String fileNameURL = URLEncoder.encode(exportFileName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+fileNameURL+";"+"filename*=utf-8''"+fileNameURL);

            //response.setContentType("application/vnd.ms-excel;charset=UTF-8");//类型
            response.setContentType("application/vnd.ms-excel");
            //response.setHeader("Content-Disposition", "attachment;filename=" + fileNames);//设置响应头
            //response.setCharacterEncoding("UTF-8");//格式
            OutputStream os = response.getOutputStream();

            workbook.write(os);//写入
            os.flush();
            /**flush指的刷新此输出流并强制写出所有缓冲的输出字节。 flush 的常规协定是：如果此输出流的实现已经缓冲了以前写入的任何字节，则调用此方法指示应将这些字节立即写入它们预期的目标。
             如果此流的预期目标是由基础操作系统提供的一个抽象（如一个文件），则刷新此流只能保证将以前写入到流的字节传递给操作系统进行写入，但不保证能将这些字节实际写入到物理设备（如磁盘驱动器）。**/
            try {
                os.close();//关闭
            } catch (Exception e) {
                e.printStackTrace();
            }
            return ServerResponse.createBySuccess();
        } catch (Exception ex) {
            ex.printStackTrace();
            return ServerResponse.createByError();
        }



    }


    //温度类型
    @PostMapping("/wdList")
    public ServerResponse wdList(@RequestBody String data,HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }

        JSONObject jsonObject = JSONObject.parseObject(data);
        if ((jsonObject.getDate("readTimeBegin") == null || jsonObject.getDate("readTimeBegin").equals(""))
                && (jsonObject.getDate("readTimeEnd") == null || jsonObject.getDate("readTimeEnd").equals(""))  ) {
            String devicetype = jsonObject.getString("devicetype");
            TypeTjDateVo typeTjDateVo = new TypeTjDateVo();


            ArrayList<TyoeListDateVo> tyoeListDateVos = new ArrayList<TyoeListDateVo>();
            List<String>  sixday = apiService.sixday();
            List<String> lasttime = new ArrayList<>();
            for (String vbs:sixday
            ) {
                List<String> timesss = apiService.findSixDay(vbs);
                for (String timetime:timesss
                ) {
                    lasttime.add(timetime);
                }
            }



            //List<String> time = apiService.findwdList(vs);
            ArrayList<String> timelist = new ArrayList<>();
            ArrayList<String> devicename = new ArrayList<>();
            List<MainTain> alldeviceListAll = apiService.findAlldeviceListAllnew(devicetype);

            for (MainTain asa : alldeviceListAll
            ) {
                //


                devicename.add(asa.getDeviceName());
                //拿到每一个 设备名称的时候
                String deviceNumber = asa.getDeviceNumber();
                ArrayList<Integer> lastfloat = new ArrayList<>();
                for (String as2 : lasttime
                ) {
                    //根据名称寻找 map
                    Integer lastVal = apiService.findvalue(as2, deviceNumber);
                    if (lastVal == null) {
                        lastVal = 0;
                    }
                    lastfloat.add(lastVal);
                }

                TyoeListDateVo tyoeListDateVo = new TyoeListDateVo();
                tyoeListDateVo.setName(asa.getDeviceName());
                tyoeListDateVo.setData(lastfloat);
                tyoeListDateVos.add(tyoeListDateVo);

            }

            for (String as : lasttime
            ) {

                timelist.add(as);
                //找到每一个设备


            }
            typeTjDateVo.setTime(timelist);
            typeTjDateVo.setDeviceName(devicename);
            typeTjDateVo.setTyoeListDateVo(tyoeListDateVos);
            return ServerResponse.createBySuccess(typeTjDateVo);
        }

        Date readTimeBegin = jsonObject.getDate("readTimeBegin");
        Date readTimeEnd = jsonObject.getDate("readTimeEnd");
        //判断 = 1 取 300 个时间
        //如果  > 1 每天取 42
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");

        System.out.println(differentDays(readTimeBegin,readTimeEnd));



        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String formatBegin = sdf.format(readTimeBegin);
        String formatEnd = sdf.format(readTimeEnd);
        //根据时间区间 查询
        String devicetype = jsonObject.getString("devicetype");
        TypeTjDateVo typeTjDateVo = new TypeTjDateVo();

        ArrayList<TyoeListDateVo> tyoeListDateVos = new ArrayList<TyoeListDateVo>();
        List<String> time = apiService.findwdList2(formatBegin,formatEnd);
        List<String> lasttime = new ArrayList<>();
        for (String vbs:time
        ) {
            List<String> timesss = apiService.findSixDay2(vbs);
            for (String timetime:timesss
            ) {
                lasttime.add(timetime);
            }
        }



        //List<String> time = apiService.findwdList(vs);
        ArrayList<String> timelist = new ArrayList<>();
        ArrayList<String> devicename = new ArrayList<>();
        List<MainTain> alldeviceListAll = apiService.findAlldeviceListAllnew(devicetype);

        for (MainTain asa : alldeviceListAll
        ) {
            //


            devicename.add(asa.getDeviceName());
            //拿到每一个 设备名称的时候
            String deviceNumber = asa.getDeviceNumber();
            ArrayList<Integer> lastfloat = new ArrayList<>();
            for (String as2 : lasttime
            ) {
                //根据名称寻找 map
                Integer lastVal = apiService.findvalue(as2, deviceNumber);
                if (lastVal == null) {
                    lastVal = 0;
                }
                lastfloat.add(lastVal);
            }

            TyoeListDateVo tyoeListDateVo = new TyoeListDateVo();
            tyoeListDateVo.setName(asa.getDeviceName());
            tyoeListDateVo.setData(lastfloat);
            tyoeListDateVos.add(tyoeListDateVo);

        }

        for (String as : lasttime
        ) {

            timelist.add(as);
            //找到每一个设备


        }
        typeTjDateVo.setTime(timelist);
        typeTjDateVo.setDeviceName(devicename);
        typeTjDateVo.setTyoeListDateVo(tyoeListDateVos);
        return ServerResponse.createBySuccess(typeTjDateVo);
    }

    //温度类型
    @PostMapping("/wdLists")
    public ServerResponse wdLists(@RequestBody String data,HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ") + 1);
        User u = JwtUtil.unsign(jwt, User.class);
        if (u == null) {
            return ServerResponse.createByErrorMsg("token无效");
        }

        JSONObject jsonObject = JSONObject.parseObject(data);
        if ((jsonObject.getDate("readTimeBegin") == null || jsonObject.getDate("readTimeBegin").equals(""))
             && (jsonObject.getDate("readTimeEnd") == null || jsonObject.getDate("readTimeEnd").equals(""))  ) {
            String devicetype = jsonObject.getString("devicetype");
            TypeTjDateVo typeTjDateVo = new TypeTjDateVo();


            ArrayList<TyoeListDateVo> tyoeListDateVos = new ArrayList<TyoeListDateVo>();
            List<String>  sixday = apiService.sixday();
            List<String> lasttime = new ArrayList<>();
            for (String vbs:sixday
                 ) {
                List<String> timesss = apiService.findSixDay(vbs);
                for (String timetime:timesss
                     ) {
                    lasttime.add(timetime);
                }
            }



            //List<String> time = apiService.findwdList(vs);
            ArrayList<String> timelist = new ArrayList<>();
            ArrayList<String> devicename = new ArrayList<>();
            List<MainTain> alldeviceListAll = apiService.findAlldeviceListAllnew(devicetype);

            for (MainTain asa : alldeviceListAll
            ) {
                //


                devicename.add(asa.getDeviceName());
                //拿到每一个 设备名称的时候
                String deviceNumber = asa.getDeviceNumber();
                ArrayList<Integer> lastfloat = new ArrayList<>();
                for (String as2 : lasttime
                ) {
                    //根据名称寻找 map
                    Integer lastVal = apiService.findvalue(as2, deviceNumber);
                    if (lastVal == null) {
                        lastVal = 0;
                    }
                    lastfloat.add(lastVal);
                }

                TyoeListDateVo tyoeListDateVo = new TyoeListDateVo();
                tyoeListDateVo.setName(asa.getDeviceName());
                tyoeListDateVo.setData(lastfloat);
                tyoeListDateVos.add(tyoeListDateVo);

            }

            for (String as : lasttime
            ) {

                timelist.add(as);
                //找到每一个设备


            }
            typeTjDateVo.setTime(timelist);
            typeTjDateVo.setDeviceName(devicename);
            typeTjDateVo.setTyoeListDateVo(tyoeListDateVos);
            return ServerResponse.createBySuccess(typeTjDateVo);
        }

        Date readTimeBegin = jsonObject.getDate("readTimeBegin");
        Date readTimeEnd = jsonObject.getDate("readTimeEnd");
        //判断 = 1 取 300 个时间
        //如果  > 1 每天取 42
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");

        System.out.println(differentDays(readTimeEnd,readTimeBegin));



        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String formatBegin = sdf.format(readTimeBegin);
        String formatEnd = sdf.format(readTimeEnd);
        //根据时间区间 查询
        String devicetype = jsonObject.getString("devicetype");
        TypeTjDateVo typeTjDateVo = new TypeTjDateVo();

        ArrayList<TyoeListDateVo> tyoeListDateVos = new ArrayList<TyoeListDateVo>();
        List<String> time = apiService.findwdList2(formatBegin,formatEnd);
        ArrayList<String> timelist = new ArrayList<>();
        ArrayList<String> devicename = new ArrayList<>();
        List<MainTain> alldeviceListAll = apiService.findAlldeviceListAllnew(devicetype);

        for (MainTain asa : alldeviceListAll
        ) {
            //


            devicename.add(asa.getDeviceName());
            //拿到每一个 设备名称的时候
            String deviceNumber = asa.getDeviceNumber();
            ArrayList<Integer> lastfloat = new ArrayList<>();
            for (String as2 : time
            ) {
                //根据名称寻找 map
                Integer lastVal = apiService.findvalue(as2, deviceNumber);
                if (lastVal == null) {
                    lastVal = 0;
                }
                lastfloat.add(lastVal);
            }

            TyoeListDateVo tyoeListDateVo = new TyoeListDateVo();
            tyoeListDateVo.setName(asa.getDeviceName());
            tyoeListDateVo.setData(lastfloat);

            tyoeListDateVos.add(tyoeListDateVo);

        }

        for (String as : time
        ) {

            timelist.add(as);
            //找到每一个设备


        }
        typeTjDateVo.setTime(timelist);
        typeTjDateVo.setDeviceName(devicename);
        typeTjDateVo.setTyoeListDateVo(tyoeListDateVos);
        return ServerResponse.createBySuccess(typeTjDateVo);
    }

    public static int differentDays(Date date1,Date date2){
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(date1);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(date2);

        int day1 = calendar1.get(Calendar.DAY_OF_YEAR);
        int day2 = calendar2.get(Calendar.DAY_OF_YEAR);
        int year1 = calendar1.get(Calendar.YEAR);
        int year2 = calendar2.get(Calendar.YEAR);

        if (year1 != year2)  //不同年
        {
            int timeDistance = 0;
            for (int i = year1 ; i < year2 ;i++){ //闰年
                if (i%4==0 && i%100!=0||i%400==0){
                    timeDistance += 366;
                }else { // 不是闰年
                    timeDistance += 365;
                }
            }
            return  timeDistance + (day2-day1);
        }else{// 同年
            return day2-day1;
        }

    }


}
